package org.dizena.config;

import com.alibaba.fastjson2.support.spring.data.redis.GenericFastJsonRedisSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{

    @Value("${spring.redis.cacheTime}")
    private Long redisCacheSecond;

    /**
     * 声明式缓存-没有自动时间限制，永久存储；所以适合手动存-删；
     */
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, ?> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory)
    {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();

        template.setDefaultSerializer(serializer);
        template.setStringSerializer(stringRedisSerializer);

        template.setKeySerializer(stringRedisSerializer);
        template.setValueSerializer(serializer);

        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(serializer);

        template.setEnableTransactionSupport(true);
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 注解使用的缓存，时间限制是配置的秒数
     */
    @Bean
    public RedisCacheManager redisCacheManager(LettuceConnectionFactory lettuceConnectionFactory)
    {
        //ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> objectSerializationPair = RedisSerializationContext.SerializationPair.fromSerializer(serializer);
        return RedisCacheManager.builder(lettuceConnectionFactory).cacheDefaults(RedisCacheConfiguration.defaultCacheConfig(Thread.currentThread().getContextClassLoader()).serializeValuesWith(objectSerializationPair).entryTtl(Duration.ofSeconds(redisCacheSecond))).build();
    }

}
